//
//  EPCNetworking.swift
//  Weibo
//
//  Created by LioWu on 07/04/2017.
//  Copyright © 2017 MyGit. All rights reserved.
//

import UIKit
import AFNetworking

enum EPCHttpMethod {
    case GET
    case POST
}

class EPCNetworking: AFHTTPSessionManager {
    
    static let shareManager: EPCNetworking = {
        
        let instance = EPCNetworking()
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    lazy var userAccount:EPCUserAccount = EPCUserAccount()
    
    /// user is logon
    var userLogon: Bool {
        return userAccount.access_token != nil
    }
    
    func tokenRequest(method:EPCHttpMethod = .GET, URLString: String, parameters:[String: AnyObject]?, progress:((Progress) -> Swift.Void)?, completeHandler:@escaping (_ response:AnyObject?, _ isSuccess:Bool) -> ()) {
        
        // no token
        guard let token = userAccount.access_token else {
            
            NotificationCenter.default.post(
                name: Notification.Name(EPCUserShouldLoginNotification),
                object: nil)
            
            completeHandler(nil, false)
            return
        }
        
        var params = parameters
        
        if params == nil {
            params = [String: AnyObject]()
        }
        
        params!["access_token"] = token as AnyObject?
        
        request(method: method, URLString: URLString, parameters: params, progress: progress, completeHandler: completeHandler)
    }

    /// request: GET/POST
    ///
    /// - Parameters:
    ///   - method: GET/POST, default:GET
    ///   - URLString: url
    ///   - parameters: parameters
    ///   - progress: progress
    ///   - completeHandler: (response, isSuccess) -> ()
    func request(method:EPCHttpMethod = .GET, URLString: String, parameters:[String: AnyObject]?, progress:((Progress) -> Swift.Void)?, completeHandler:@escaping (_ response:AnyObject?, _ isSuccess:Bool) -> ()) {
        
        let success = { (dataTask:URLSessionDataTask, response:Any?) ->() in
            completeHandler(response as AnyObject?, true)
        }
        
        let failure = { (dataTask:URLSessionDataTask?, error:Error) ->() in
            
            // 403 token invalid
            if (dataTask?.response as? HTTPURLResponse)?.statusCode == 403 {
                debugPrint("token过期, 需要再次登录")
                
                NotificationCenter.default.post(
                    name: Notification.Name(EPCUserShouldLoginNotification),
                    object: "token invalid")
                
                return
            }
            
            print("网络错误：\(error)")
            
            completeHandler(nil, false)
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: progress, success: success, failure: failure)
        }
        else {
            post(URLString, parameters: parameters, progress: progress, success: success, failure: failure)
        }
    }
}
